package com.woniu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.github.pagehelper.PageInfo;
import com.woniu.entity.FlowerOrder;
import com.woniu.service.FlowerOrderService;
import com.woniu.util.R;
import com.woniu.vo.OrderVoCZT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/flowerOrder")
@Api(value = "订单接口", tags = "订单功能")
public class FlowerOrderController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private FlowerOrderService fos;
    @Resource
    private AlipayClient alipayClient;

    @ApiOperation("购物车新增订单及订单详情")
    @PostMapping("insertFlowerOrderFromCart")
    public R insertFlowerOrderFromCart(int[] cartIds, int accountId) {
        Long i = fos.insertFlowerOrderFromCart(accountId, cartIds);
        if (i != 0 && i != 1L) {
            Set<String> set = redisTemplate.keys("orderSelect*");
            if (set == null || set.size() == 0) {
            } else {
                redisTemplate.delete(set);
            }
            Set<String> set1 = redisTemplate.keys("cartSelect*");
            if (set1 == null || set1.size() == 0) {
            } else {
                redisTemplate.delete(set1);
            }
            Set<String> set2 = redisTemplate.keys("flowerSelect*");
            if (set1 == null || set2.size() == 0) {
            } else {
                redisTemplate.delete(set2);
            }
            String s = String.valueOf(i);
            return R.build(200, "下单成功", s);
        } else if (i == 1L) {
            return R.build(300, "无默认收货地址,请新增收货地址", null);
        } else {
            return R.error("下单失败");
        }
    }

    @ApiOperation("直接下单新增订单及订单详情")
    @PostMapping("insertFlowerOrderFromFlowerInfo")
    public R insertFlowerOrderFromFlowerInfo(int accountId, int buyCount, int flowerId, BigDecimal flowerPrice) {
        Long i = fos.insertFlowerOrderFromFlowerInfo(accountId, buyCount, flowerId, flowerPrice);
        if (i != 0&&i!=1L) {
            Set<String> set = redisTemplate.keys("orderSelect*");
            if (set == null || set.size() == 0) {
            } else {
                redisTemplate.delete(set);
            }
            Set<String> set1 = redisTemplate.keys("cartSelect*");
            if (set1 == null || set1.size() == 0) {
            } else {
                redisTemplate.delete(set1);
            }
            Set<String> set2 = redisTemplate.keys("flowerSelect*");
            if (set1 == null || set2.size() == 0) {
            } else {
                redisTemplate.delete(set2);
            }
            String s = String.valueOf(i);
            return R.build(200, "下单成功", s);
        } else if (i == 1L) {
            return R.build(300, "无默认收货地址,请新增收货地址", null);
        } else {
            return R.error("下单失败");
        }
    }

    @ApiOperation("根据订单号查询订单信息")
    @GetMapping("selectOrderByOrderId")
    public R selectOrderByOrderId(String orderId) {
        Object temp = redisTemplate.opsForValue().get("orderSelect:" + orderId);
        if (temp != null) {
            return R.build(200, "查询成功", temp);
        } else {
            OrderVoCZT vo = fos.selectOrderByOrderId(orderId);
            redisTemplate.opsForValue().set("orderSelect:" + orderId, vo);
            redisTemplate.expire("orderSelect:" + orderId, 30, TimeUnit.MINUTES);
            return R.build(200, "查询成功", vo);
        }
    }

    @ApiOperation("根据订单号修改收货地址")
    @PostMapping("updateAddressIdByOrderId")
    public R updateAddressIdByOrderId(String orderId, int addressId) {
        int update = fos.updateAddressIdByOrderId(orderId, addressId);
        if (update > 0) {
            Set<String> set = redisTemplate.keys("orderSelect*");
            if (set == null || set.size() == 0) {
                return R.success("修改收货地址成功");
            }
            redisTemplate.delete(set);
            return R.success("修改收货地址成功");
        } else {
            return R.error("修改收货地址失败");
        }
    }

    @ApiOperation("根据订单号修改备注")
    @PostMapping("updateOrderByOrderId")
    public R updateOrderByOrderId(String orderId, String remark) {
        FlowerOrder order = new FlowerOrder();
        order.setOrderId(Long.valueOf(orderId));
        order.setRemark(remark);
        int update = fos.updateOrderByOrderId(order);
        if (update > 0) {
            Set<String> set = redisTemplate.keys("orderSelect*");
            if (set == null || set.size() == 0) {
                return R.success("修改备注成功");
            }
            redisTemplate.delete(set);
            return R.success("修改备注成功");
        } else {
            return R.error("修改备注失败");
        }
    }

    @ApiOperation("根据用户id查询订单信息")
    @GetMapping("selectAllOrderByAccountId")
    public R selectAllOrderByAccountId(int accountId,
                                       @RequestParam(defaultValue = "") String orderId,
                                       @RequestParam(defaultValue = "2") int isComment,
                                       @RequestParam(defaultValue = "") String startTime,
                                       @RequestParam(defaultValue = "") String endTime,
                                       @RequestParam(defaultValue = "0") int status,
                                       int pageNum,
                                       int pageSize) {
        if (startTime != null && endTime != null && !startTime.isEmpty() && !endTime.isEmpty()) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(startTime, DateTimeFormatter.ISO_DATE_TIME)
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
            startTime = zonedDateTime.format(formatter);
            System.out.println(startTime);

            ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(endTime, DateTimeFormatter.ISO_DATE_TIME)
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
            endTime = zonedDateTime1.format(formatter);
            System.out.println(endTime);
        }
        PageInfo<OrderVoCZT> pageInfo = fos.selectAllOrderByAccountId(accountId, orderId, (byte) isComment, startTime, endTime, status, pageNum, pageSize);
        return R.build(200, "查询成功", pageInfo);
    }

    @ApiOperation("确认收货")
    @PostMapping("updateStatusByOrderId")
    public R updateStatusByOrderId(String orderId) {
        FlowerOrder order = new FlowerOrder();
        order.setOrderId(Long.valueOf(orderId));
        order.setStatus((byte) 5);
        Integer update = fos.updateOrderByOrderId(order);
        if (update > 0) {
            Set<String> set = redisTemplate.keys("orderSelect*");
            if (set == null || set.size() == 0) {
                return R.success("确认收货成功");
            }
            redisTemplate.delete(set);
            return R.success("确认收货成功");
        } else {
            return R.error("确认收货失败");
        }
    }

    @ApiOperation("根据订单编号删除订单")
    @PostMapping("deleteOrderByOrderId")
    public R deleteOrderByOrderId(String orderId) throws AlipayApiException {
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + Long.valueOf(orderId) + "\"}");
        //请求
        AlipayTradeQueryResponse execute = alipayClient.execute(alipayRequest);
        String code = execute.getCode();
        Date sendPayDate = execute.getSendPayDate();
        if (!"10000".equals(code) || sendPayDate == null) {
            int delete = fos.deleteOrderByOrderId(orderId);
            if (delete > 0) {
                Set<String> set = redisTemplate.keys("orderSelect*");
                if (set == null || set.size() == 0) {
                    return R.success("订单取消成功");
                }
                redisTemplate.delete(set);
                return R.success("订单取消成功");
            } else {
                return R.error("订单取消失败");
            }
        } else {
            FlowerOrder order = new FlowerOrder();
            order.setOrderId(Long.valueOf(orderId));
            order.setStatus((byte) 2);
            fos.updateOrderByOrderId(order);
            Set<String> set = redisTemplate.keys("orderSelect*");
            if (set == null || set.size() == 0) {
                return R.build(900, "订单已支付，无法取消", null);
            }
            redisTemplate.delete(set);
            return R.build(900, "订单已支付，无法取消", null);
        }
    }

}
